'''
用于挑选一个好的二值图
'''
import cv2
import numpy as np
import os

def refine(img_path):
    img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
    # thresh, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    thresh, img = cv2.threshold(img, 50, 150, cv2.THRESH_BINARY)
    h, w = img.shape[0:2]
    #前景背景反转
    # for i in range(h):
    #     for j in range(w):
    #         if img[i, j] == 255:
    #             img[i, j] = 0
    #         else:
    #             img[i, j] = 255
    cv2.namedWindow("binary", 0)
    cv2.resizeWindow("binary", 640, 480)
    cv2.imshow('binary', img)
    dst = img.copy()

    num_erode = 0

    while (True):
        if np.sum(dst) == 0:
            break
        kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
        dst = cv2.erode(dst, kernel)
        cv2.namedWindow("z", 0)
        cv2.resizeWindow("z", 640, 480)
        cv2.imshow('z', dst)
        c = cv2.waitKey(0)
        if c == ord("q"):
            print("保存")
            cv2.imwrite("./refine.png", dst)
            break
        num_erode = num_erode + 1

if __name__ == '__main__':
    refine(r"data\010_0000.jpg")
